"""
用户相关接口路由
"""

from typing import Optional
from fastapi import APIRouter, Header, Query
from fastapi.responses import JSONResponse
from model.user_model import (
    UserRegister,
    UserLogin,
    UserUpdate,
    UserLoginResponse,
    UserDateResponse,
    User,
)
from model.message_model import Message
from utils.password_utils import (
    encrypt_password,
    verify_password,
    get_access_jwt,
    get_user_id_from_jwt,
)
from db.operations import UserOperations

# 创建用户相关的子路由
router = APIRouter(
    prefix="/users",
    tags=["users"],
    responses={404: {"description": "Not found"}},
)


@router.get("/", summary="用户管理接口信息")
async def get_users_info():
    """获取用户管理接口信息和使用示例"""
    api_info = {
        "message": "用户管理API接口",
        "endpoints": {
            "GET /api/users/": "获取用户管理接口信息",
            "POST /api/users/register": "用户注册",
            "POST /api/users/login": "用户登录",
            "POST /api/users/update": "修改用户信息",
            "GET /api/users/get": "获取用户信息",
        },
        "examples": {
            "用户注册": {
                "url": "/api/users/register",
                "method": "POST",
                "body": {"username": "testuser", "password": "password123"},
                "description": "注册新用户",
            },
            "用户登录": {
                "url": "/api/users/login",
                "method": "POST",
                "header": "Bearer token",
                "body": {"username": "testuser", "password": "password123"},
                "description": "登录已注册用户",
            },
            "修改用户信息": {
                "url": "/api/users/update",
                "method": "POST",
                "header": "Bearer token",
                "body": {
                    "user_id": 1,
                    "nickname": "NewNickname",
                    "age": 30,
                    "gender": "男",
                    "password": "newpassword123",
                },
                "description": "更新用户信息",
            },
            "获取用户信息": {
                "url": "/api/users/get",
                "method": "GET",
                "header": "Bearer token",
                "description": "获取当前登录用户的信息",
            },
        },
    }
    return JSONResponse(status_code=200, content=api_info)


@router.post("/register", summary="用户注册")
async def register(user_data: UserRegister):
    """用户注册"""
    user_ops = UserOperations()
    # 检查用户名是否已存在
    existing_users = await user_ops.batch_query_users(usernames=[user_data.username])
    if existing_users:
        return JSONResponse(
            status_code=400,
            content=Message(
                message="用户名已存在",
            ).model_dump(),
        )
    # 准备用户数据
    user_data.password = await encrypt_password(user_data.password)  # 加密密码
    insert_data = user_data.model_dump()
    # 插入用户数据
    result = await user_ops.batch_insert_users([insert_data])
    if result > 0:
        return JSONResponse(
            status_code=200,
            content=Message(
                message="注册成功",
            ).model_dump(),
        )
    else:
        return JSONResponse(
            status_code=500,
            content=Message(
                message="注册失败，请稍后再试",
            ).model_dump(),
        )


@router.post("/login", summary="用户登录")
async def login(
    login_data: UserLogin,
    authorization: Optional[str] = Header(None, description="Bearer token"),
):
    # 去除Bearer前缀
    authorization = authorization.replace("Bearer ", "", 1) if authorization else None
    """用户登录"""
    user_id = await get_user_id_from_jwt(authorization)
    if user_id:
        # 如果提供了正确的cookie，直接返回登录成功
        return JSONResponse(
            status_code=200,
            content=UserLoginResponse(
                message="登入成功",
                token=authorization,
            ).model_dump(),
        )

    user_ops = UserOperations()
    # 查询用户
    if login_data.username:
        users = await user_ops.batch_query_users(usernames=[login_data.username])
    else:
        return JSONResponse(
            status_code=400,
            content=Message(
                message="用户名不能为空",
            ).model_dump(),
        )
    if not users:
        return JSONResponse(
            status_code=401,
            content=Message(
                message="用户名或密码错误",
            ).model_dump(),
        )
    user = users[0]
    # 验证密码
    if not await verify_password(user["password"], login_data.password):
        return JSONResponse(
            status_code=401,
            content=Message(
                message="用户名或密码错误",
            ).model_dump(),
        )

    cookie_value = await get_access_jwt(user["user_id"])

    return JSONResponse(
        status_code=200,
        content=UserLoginResponse(
            message="登入成功",
            token=cookie_value,
        ).model_dump(),
    )


@router.post("/update", summary="修改用户信息")
async def update_user(
    update_data: UserUpdate,
    authorization: Optional[str] = Header(None, description="Bearer token"),
):
    # 去除Bearer前缀
    authorization = authorization.replace("Bearer ", "", 1) if authorization else None
    """修改用户信息"""
    # 验证用户是否已登录
    user_id_from_jwt = await get_user_id_from_jwt(authorization)

    if not user_id_from_jwt:
        return JSONResponse(
            status_code=401,
            content=Message(
                message="未授权，请先登入",
            ).model_dump(),
        )
    user_ops = UserOperations()
    # 检查用户是否存在
    existing_users = await user_ops.batch_query_users(user_ids=[user_id_from_jwt])
    if not existing_users:
        return JSONResponse(
            status_code=404,
            content=Message(
                message="用户不存在",
            ).model_dump(),
        )
    # 准备更新数据
    update_dict = {"user_id": user_id_from_jwt}

    if update_data.nickname is not None:
        update_dict["nickname"] = update_data.nickname

    if update_data.age is not None:
        update_dict["age"] = update_data.age

    if update_data.gender is not None:
        update_dict["gender"] = update_data.gender

    if update_data.password is not None:
        update_dict["password"] = await encrypt_password(update_data.password)

    # 如果没有要更新的字段
    if len(update_dict) == 1:  # 只有user_id
        return JSONResponse(
            status_code=400,
            content=Message(
                message="无更新请求",
            ),
        )

    # 添加更新时间戳
    update_dict["updated_at"] = update_data.updated_at
    # 执行更新
    result = await user_ops.batch_update_users([update_dict])
    if result > 0:
        # 返回更新后的用户信息
        updated_users = await user_ops.batch_query_users(user_ids=[user_id_from_jwt])

        return JSONResponse(
            status_code=200,
            content=UserDateResponse(
                message="更新成功",
                user_data=updated_users[0],
            ).model_dump(),
        )
    else:
        return JSONResponse(
            status_code=500,
            content=Message(
                message="更新失败，请稍后再试",
            ).model_dump(),
        )


@router.get("/get", summary="获取用户信息")
async def get_user(
    authorization: Optional[str] = Header(None, description="Bearer token"),
):
    # 去除Bearer前缀
    authorization = authorization.replace("Bearer ", "", 1) if authorization else None
    """获取用户信息"""
    # 验证用户是否已登录
    user_id_from_jwt = await get_user_id_from_jwt(authorization)

    if not user_id_from_jwt:
        return JSONResponse(
            status_code=401,
            content=Message(
                message="未授权，请先登入",
            ).model_dump(),
        )

    user_ops = UserOperations()
    users = await user_ops.batch_query_users(user_ids=[user_id_from_jwt])
    if not users:
        return JSONResponse(
            status_code=404,
            content=Message(
                message="用户不存在",
            ).model_dump(),
        )

    # 返回用户信息
    return JSONResponse(
        status_code=200,
        content=UserDateResponse(
            message="获取用户信息成功",
            user_data=User(**users[0]),
        ).model_dump(),
    )
